import 'dart:convert';

import 'package:novel_reader/utils/http_util.dart';

class BiaduApi {
  static String acsToken =
      "1755972006592_1756040365373_tUr/e1IY60I+VY3/pJeN8ZU5fAbDp/feXydIm3aIP7USvRhfEqbwH9SOERtaXkmRHid3SAxwoeRgyAZujYou24ACliUKy2140mijja9IFmM6k9MQiHMOZSJk5t5KeANLkE9DH0FJoymUJdpthB/DBXElCESG3HmG16S3bXzmQYACUNuZjsl7d8MP2KEz6RkFLyDStjFwowhMZIRuQYwLkZwk/jYG8dD9f/PzBFnq5C5zItMULKEH7aBozwC9dx0jLm1c7k6g4ejTaun0d4J8xzroUxWqmnf8rP6ysFC9hikIY2/hEDL+TdY9Asli2Xc1SS1BgybA+swlUeSYsPu9kTyt3oXDwFVT17fPd6MgxgAhvqTr0TGnfkyd1OIVLE6peDIxwxixAyZIcRwaPHhJhVg9Vqr3vA8T02xjVotGQ0vgMJeL+C75WER+o8bpTqMFIawnB9pAmh5P5h6ide7Ns8brInXAKzQ8AAtKMujUr2PLJwyFQSi5pHU0pLpPYzOU";

  static Future<String> baiduTranslate(String content) async {
    List<String> lines = content.split("\n");
    var sb = StringBuffer();
    var sb2 = StringBuffer();
    for (var line in lines) {
      if (line.isNotEmpty) {
        if (sb.length >= 4500) {
          sb2.write(await _tryTranslate(sb.toString()));
          sb2.write("\n");
          sb = StringBuffer();
        }
        sb.write(line);
        sb.write("\n");
      } else {
        sb.write("\n");
      }
    }
    if (sb.length > 0) {
      sb2.write(await _tryTranslate(sb.toString()));
    }
    return sb2.toString();
  }

  static Future<String> _tryTranslate(String str) async {
    int count = 0;
    while (count++ < 5) {
      try {
        String result = await _baiduTranslate(str);
        if (result.isNotEmpty) {
          return result;
        }
      } catch (e) {
        //
      }
    }
    return str;
  }

  static Future<String> _baiduTranslate(String s) async {
    var sb = StringBuffer();
    Map<String, dynamic> json = {
      "from": "jp",
      "to": "zh",
      "reference": "",
      "query": s,
      "domain": "common",
      "corpusIds": [],
      "needPhonetic": false,
      "milliTimestamp": DateTime.now().millisecond,
    };
    Map<String, String> header = {
      "Accept-Language": "zh-CN,zh;q=0.9",
      "Acs-Token": acsToken,
      "Content-Type": "application/json; charset=UTF-8",
      "Sec-Ch-Ua":
          "\"Not)A;Brand\";v=\"8\", \"Chromium\";v=\"138\", \"Microsoft Edge\";v=\"138\"",
      "accept": "text/event-stream",
      "Referer":
          'https://fanyi.baidu.com/mtpe-individual/transText?query=${Uri.encodeComponent(s)}&lang=jp2zh&ext_channel=Aldtype',
      "User-Agent":
          "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36 Edg/138.0.0.0",
    };
    var response = await HttpUtil.post(
      url: "https://fanyi.baidu.com/ait/text/translate",
      data: json,
      headers: header,
    );
    var pattern = RegExp(r"^(\\s|　)+");
    for (var line in response.data.split("\n")) {
      if (line.startsWith("data:")) {
        Map<String, dynamic> data = jsonDecode(line.substring(6))["data"];
        if ("Translating" == data["event"]) {
          List<Map<String, dynamic>> arr = data["list"];
          for (var item in arr) {
            String src = item['src'];
            RegExpMatch? matcher = pattern.firstMatch(src);
            if (matcher != null) {
              sb.write(matcher.group(0));
              sb.write("\n");
            }
            sb.write(item["dst"]);
            sb.write("\n");
          }
          break;
        }
      }
    }
    return sb.toString();
  }
}
